package com.lzy.business.facade;/**
 * Created by Administrator on 2017/11/30 0030.
 */

import com.lzy.base.apis.SysUserRoleServiceApi;
import com.lzy.base.dtos.SysUserAdminDto;
import com.lzy.base.dtos.SysUserRoleDto;
import com.lzy.base.entity.SysUserAdmin;
import com.lzy.base.service.SysUserAdminService;
import com.lzy.base.utils.UserUtil;
import com.lzy.framework.core.utils.DozerUtils;
import com.lzy.framework.core.utils.StringUtil;
import com.lzy.product.apis.ProductUserServiceApi;
import com.lzy.product.constants.BusinessType;
import com.lzy.product.dtos.ProductUserDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author: by Happy He
 * @Description:
 * @Date: Created in PM 3:06 2017/11/30 0030
 */
@Component
public class SysUserAdminServiceFacade {
    private static final Logger logger = LoggerFactory.getLogger(SysUserAdminServiceFacade.class);
    @Autowired
    private ProductUserServiceApi productUserServiceApi;
    @Autowired
    private SysUserRoleServiceApi sysUserRoleServiceApi;
    @Autowired
    private SysUserAdminService sysUserAdminService;

    @Value("${default.password}")
    private String defaultPassword;

    /**
     * 新增用户
     *
     * @param userDto
     */
    public void addUser(ProductUserDto userDto) {
        String jobNumber = sysUserAdminService.selectMaxJobNumber();
        if (jobNumber != null && !"".equals(jobNumber)) {
            userDto.setJobNumber(StringUtil.leftPad(String.valueOf(Long.parseLong(jobNumber) + 1), 4, "0"));
        } else {
            userDto.setJobNumber("0001");
        }
        if (userDto.getUserId() == null ){
            userDto.setUserId(BusinessType.SYS_USER_ADMIN_ID);
        }
        Long userId = productUserServiceApi.insert(userDto);
        //绑定用户-角色(业务员)
        SysUserRoleDto sysUserRole = new SysUserRoleDto();
        sysUserRole.setUserId(userId);
        sysUserRole.setRoleId(BusinessType.RoleType.SALESMAN.getCode());
        sysUserRoleServiceApi.addUserRole(sysUserRole);
    }

    /**
     * 修改密码
     *
     * @param sysUserAdmin
     * @param newPassword
     */
    public void editPwd(SysUserAdminDto sysUserAdmin, String newPassword) {
        SimpleDateFormat dfTime = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date dateCurrent = new Date();
        logger.info("用户ID: " + UserUtil.getCurrentUser().getId() + " 于 " + dfTime.format(dateCurrent) + " 尝试修改后台密码  ");
        sysUserAdmin.setRemark("用户ID: " + UserUtil.getCurrentUser().getId() + " 于 " + dfTime.format(dateCurrent) + " 修改后台密码 success");
        sysUserAdmin.setPassword(newPassword);
        //修改后台用户登录密码
        sysUserAdminService.updatePassword(DozerUtils.map(sysUserAdmin, SysUserAdmin.class));
    }
}


